package com.xiaoyong.system.util;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

//JWT工具类
public class JwtUtil {

    //有效期为
    public static final Long JWT_TTL =3600000L;//60 * 60 *1000  一个小时
    //设置密钥明文
    public static final String JWT_KEY="itcast";


    public static String createJWT(String id,String subject,Long ttlMillis){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long  nowMillis= System.currentTimeMillis();
        Date date = new Date(nowMillis);
        if (ttlMillis==null){
            ttlMillis=JwtUtil.JWT_TTL;
        }
        long expMillis=nowMillis+ttlMillis;
        Date expDate = new Date(expMillis);
        SecretKey secretKey=generalkey();
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(id)//唯一id
                .setSubject(subject)//主题，可以是JSON数据
                .setIssuer("admin")//签发者
                .setIssuedAt(date)//签发时间
                .signWith(signatureAlgorithm, secretKey)//使用HS256对称的加密算法签名，第二个参数为私密
                .setExpiration(expDate);//设置过期时间
        return jwtBuilder.compact();
    }

    //生成后的密钥
    public static SecretKey generalkey(){
        byte[] decode = Base64.getDecoder().decode(JWT_KEY);
        SecretKeySpec keySpec = new SecretKeySpec(decode, 0, decode.length, "AES");
        return keySpec;
    }
}
